<template>
  <div class="content-page">
    <div class="content-main">
      <div class="form-table-box">
        <el-form ref="infoForm" :rules="infoRules" :model="infoForm" label-width="120px">
          <el-form-item label="视频名称" prop="videoName">
            <el-input v-model="infoForm.videoName" />
          </el-form-item>
          <el-form-item label="所属分类" prop="categoryId">
            <el-select v-model="infoForm.categoryId" placeholder="请选择分类">
              <el-option
                v-for="(item,index) in categoryList"
                :key="index"
                :label="item.category"
                :value="item.categoryId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="封面" prop="showImage">
            <div class="flex align-items">
              <div v-if="infoForm.showImage" class="pos-r">
                <el-image
                  :src="infoForm.showImage"
                  class="image-show"
                  style="width: 165px;height: 105px;"
                />
                <i class="el-icon-error pos-a delBtn" @click="delBtnFun" />
              </div>
              <el-upload
                v-else
                :action="imgServer"
                :on-success="handleUploadImageSuccess"
                :limit="1"
                :on-progress="uploadingImgAction"
                :on-remove="handleRemove"
                :before-upload="beforeUpload"
                class="image-uploader"
                name="upfile"
              >
                <i class="el-icon-plus image-uploader-icon" />
                <div
                  slot="tip"
                  class="el-upload__tip"
                >{{ uploadingImgStatus?'压缩中...请稍等':'图片尺寸:678*380 大小限制:2M以内' }}</div>
              </el-upload>
            </div>
          </el-form-item>
          <el-form-item label="封面显示">
            <el-radio-group v-model="infoForm.showMode">
              <el-radio :label="2" name="type">大图</el-radio>
              <el-radio :label="1" name="type">小图</el-radio>
              <el-radio :label="0" name="type">无图</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="视频文件">
            <div class="upload-demo">
              <div
                class="el-upload el-upload--text txt-l"
                @click="handleClick"
                @keydown="handleKeydown"
              >
                <el-button
                  slot="trigger"
                  size="small"
                  type="primary"
                  class="el-button el-button--primary el-button--small"
                >选取文件</el-button>
                <input
                  ref="input"
                  type="file"
                  name="file"
                  class="el-upload__input"
                  @change="handleChange"
                >
                <div slot="tip" class="el-upload__tip">上传视频请提前压缩</div>
              </div>
            </div>
            <div v-if="infoForm.videoUrl" style="width: 618px;height: 350px;">
              <video-player
                ref="videoPlayer"
                :playsinline="true"
                :options="video_Config"
                class="video-player vjs-custom-skin"
              />
            </div>
          </el-form-item>
          <el-form-item labe>
            "视频简介" prop="simple_desc">
            <div class="ueditor-wrap">
              <vue-ueditor-wrap
                v-model="msg"
                :config="ueditorConfig.config"
                @ready="ueditorConfig.ready"
              />
            </div>
            <div class="form-tip" />
          </el-form-item>
          <el-form-item label="显示状态">
            <el-radio-group v-model="infoForm.showVideoMode">
              <el-radio :label="1" name="type">显示</el-radio>
              <el-radio :label="0" name="type">隐藏</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否推荐">
            <el-radio-group v-model="infoForm.recommendFlag">
              <el-radio :label="1" name="type">是</el-radio>
              <el-radio :label="0" name="type">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="排序">
            <el-input-number v-model="infoForm.sorting" :min="0" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmitInfo">确定保存</el-button>
            <el-button @click="goBackPage">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <el-dialog
      :visible.sync="dialogVisible"
      :show-close="false"
      :close-on-click-modal="false"
      title="视频模块"
      width="30%"
    >
      <div class="progressContent">
        <el-progress v-if="!change_video_status" :percentage="videoPercentage" />
        <div v-if="!change_video_status" class="mt10">文件上传中</div>
        <div v-else class="mt10">服务器转码中...</div>
        <div class="mt10">请耐心等待</div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  // getCategoryList,
  addVideo,
  getVideoToken,
  setVideoPfop,
  getVideoPfopStatus
} from '@/api/video'
import ueditorConfig from '@/config/ueditorConfig'
import uploadFun from '@/utils/qiniu'
import videoConfig from '@/utils/videoConfig'
export default {
  components: {},
  data() {
    return {
      categoryList: [],
      ueditorConfig: ueditorConfig,
      // imgServer: `${config.baseUrl}/vms/v1/image/upload`,
      // videoServer: `${config.baseUrl}/vms/v1/video/upload`,
      uploadingImgStatus: false,
      srcList: [],
      msg: '', // 富文本
      infoForm: {
        id: '',
        videoName: '',
        categoryId: '',
        category: '',
        showMode: 2,
        showVideoMode: 1,
        showImage: null,
        videoDesc: null, // 短视频文件
        videoUrl: null,
        sorting: null,
        recommendFlag: 0
      },
      infoRules: {
        videoName: [
          {
            required: true,
            message: '请输入名称',
            trigger: 'blur'
          }
        ],
        categoryId: [
          {
            required: true,
            message: '请选择分类',
            trigger: 'change'
          }
        ],
        showImage: [
          {
            required: true,
            message: '请上传封面',
            trigger: 'change'
          }
        ]
      },
      videoPercentage: 0,
      uploading_video: false, // 新增部分
      change_video_status: false,
      video_Config: videoConfig,
      show_video: true,
      timer: null,
      dialogVisible: false
    }
  },
  mounted() {
    const self = this
    if (self.$route.query.id) {
      self.getInfo(self.$route.query.id)
    }
    clearInterval(self.timer)
    if (!self.$store.state.video.videoToken) {
      getVideoToken().then(res => {
        self.$store.commit('SET_VIDEOTOKEN', res.data.data.token)
      })
    }
    this.getCategoryListFun()
  },
  methods: {
    uploadingImgAction(event, file, fileList) {
      const percentage = parseInt((event.loaded / event.total) * 100)
      if (percentage === 100) {
        this.uploadingImgStatus = true
      }
    },
    handleRemove() {
      this.infoForm.showImage = ''
    },
    goBackPage() {
      this.$router.push({
        name: 'goods'
      })
    },
    delBtnFun() {
      this.infoForm.showImage = ''
    },
    beforeUpload(file) {
      console.log(2222)
      const self = this
      if (file.size / (1024 * 1024) > 2) {
        self.$notify({
          title: '提示',
          message: '文件太大2M以内'
        })
        return false
      }
    },
    onSubmitInfo() {
      const self = this
      self.$refs['infoForm'].validate(valid => {
        if (valid) {
          self.infoForm.videoDesc = self.msg
          addVideo(self.infoForm)
            .then(res => {
              self.$message({
                message: '视频保存成功',
                type: 'success'
              })
              if (self.infoForm.id) {
                self.$router.push({
                  name: 'goods'
                })
              }
            })
            .catch(err => {
              console.log(err)
            })
        } else {
          return false
        }
      })
    },
    handleUploadImageSuccess(res, file) {
      this.uploadingImgStatus = false
      if (res.respCode.code === 'EDI-10000') {
        this.infoForm.showImage = res.data.fileUrl
        this.srcList = [res.data.fileUrl]
      }
    },
    // getInfo(id) {
    //   let data = JSON.parse(self.$route.params.data)
    //   // 加载商品详情
    //   const self = this
    //   getVideoInfo({
    //     id: id
    //   }).then(res => {
    //     for (const key in self.infoForm) {
    //       if (key === 'videoDesc') {
    //         self.msg = res[key]
    //       }
    //       self.video_Config[`sources`][0].src = res.videoUrl
    //       self.infoForm[key] = res[key]
    //     }
    //   })
    // },
    // getCategoryListFun() {
    //   const self = this
    //   getCategoryList({
    //     index: 0,
    //     size: 99
    //   }).then(res => {
    //     self.categoryList = res.content
    //   })
    // },
    // 文件
    handleClick() {
      this.$refs.input.value = ''
      this.$refs.input.click()
    },
    handleChange(ev) {
      const files = ev.target.files
      if (!files) return
      this.uploadFiles(files)
    },
    uploadFiles(files) {
      const self = this
      const observer = {
        next(res) {
          self.videoPercentage = parseInt(res.total.percent)
        },
        complete(res) {
          if (res.key) {
            setVideoPfop({
              key: res.key
            }).then(res => {
              self.change_video_status = true
              self.timer = setInterval(() => {
                getVideoPfopStatus({
                  id: res.data.data.persistentId
                }).then(res => {
                  res = res.data.data
                  if (res[0].status.code === 0) {
                    clearInterval(self.timer)
                    self.dialogVisible = false
                    self.change_video_status = false
                    self.video_Config[`sources`][0].src = res[0].url
                    self.infoForm.videoUrl = res[0].url
                  }
                })
              }, 1000)
            })
          }
        }
      }
      self.dialogVisible = true
      self.subscription = uploadFun(
        self.$store.state.video.videoToken,
        files[0],
        observer
      )
    },
    close() {
      const self = this
      self.change_video_show = false
      self.dialogVisible = false
      self.change_video_status = false
      if (self.subscription) {
        self.subscription.unsubscribe()
      }
      clearInterval(self.timer)
    },
    beforeDestroy() {
      clearInterval(self.timer)
    },
    handleKeydown(e) {
      if (e.target !== e.currentTarget) return
      if (e.keyCode === 13 || e.keyCode === 32) {
        this.handleClick()
      }
    }
  }
}
</script>

<style>
.image-uploader {
  min-height: 105px;
  height: auto !important;
}

.image-uploader .el-upload {
  border: 1px solid #d9d9d9;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.image-uploader .el-upload:hover {
  border-color: #20a0ff;
}

.image-uploader .image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 187px;
  height: 105px;
  line-height: 105px;
  text-align: center;
}

.image-show {
  width: 187px;
  height: 105px;
  display: block;
}

.image-uploader.new-image-uploader {
  font-size: 28px;
  color: #8c939d;
  width: 165px;
  height: 105px;
  line-height: 105px;
  text-align: center;
}

.image-uploader.new-image-uploader .image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 165px;
  height: 105px;
  line-height: 105px;
  text-align: center;
}

.delBtn {
  position: absolute;
  font-size: 24px;
  right: -12px;
  top: -12px;
  color: #ff5d6a;
  cursor: pointer;
  z-index: 999;
}
</style>
